const db = require("../models/index");
const user = require("../models/user");
const User = db.user;
const Project = db.project;
const Need = db.need;
const Bug = db.bug;
const UserProject = db.user_project;
const UserBug = db.user_bug;
const UserNeed = db.user_need;

// 创建项目
exports.newProject = async (req, res) => {
  const { projectName, detail } = req.body;
  // 获取当前用户的ID、姓名，用于作为项目创建人
  let user = req.user;
  if (!projectName) {
    return res.status(400).json({ code: 400, errorMsg: "项目名称不能为空" });
  }
  console.log('1111111111111111111111111user',user);

  try {
    // 项目名称已存在
    const project = await Project.findOne({ where: { projectName } });
    if (project) {
      return res.status(409).send({ code: 409, errorMsg: "项目名称已存在" });
    }
    // 随机生成邀请码
    const generateUniqueInvitationCode = async () => {
      let invitationCode;
      let existingProject;
      const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

      do {
        invitationCode = "";
        for (let i = 0; i < 8; i++) {
          invitationCode +=
            characters[Math.floor(Math.random() * characters.length)];
        }
        // 检查邀请码是否唯一
        existingProject = await Project.findOne({ where: { invitationCode } });
      } while (existingProject); // 如果邀请码不唯一，重新生成

      return invitationCode;
    };

    const invitationCode = await generateUniqueInvitationCode();

    // 项目创建成功，并设置邀请码
    const newProject = await Project.create({
      projectName,
      detail,
      creator: user.realName,
      creatorId: user.id,
      invitationCode, // 将生成的邀请码赋值给项目
    });

    // 创建关联
    user = await User.findOne({ where: { id: user.id } });
    await user.addMyProject(newProject);

    // 设置项目创建人为管理员,并设置projectName

    const [updatedRows] = await UserProject.update(
      { isAdmin: true, projectName: newProject.projectName },
      { where: { userId: user.id, projectId: newProject.id } }
    );

    // 确保记录被更新
    if (updatedRows === 0) {
      return res.status(404).json({
        code: 404,
        errorMsg: "No user-project association ",
      });
    }

    res.status(201).json({
      code: 201,
      msg: "项目创建成功",
      data: {
        id: newProject.id,
        projectName: newProject.projectName,
        invitationCode,
      },
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: 500, errorMsg: error.message });
  }
};

// 获取我的项目列表
exports.getMyProjects = async (req, res) => {
  const userId = req.user.id;
  console.log("当前用户ID:", userId);
  try {
    // 先查询用户是否存在
    const user = await User.findOne({
      where: { id: userId }
    });

    // 用户不存在时返回错误
    if (!user) {
      return res.status(404).json({ 
        code: 404, 
        errorMsg: "用户不存在" 
      });
    }

    // 查询用户的项目
    const MyProject = await User.findOne({
      where: { id: userId },
      attributes: [],
      include: [
        {
          model: Project,
          as: "MyProject",
          where: { status: "进行中" },
          attributes: ["id", "projectName", "createdAt", "status"],
          through: { attributes: [] },
        },
      ],
    });

    // 用户存在但没有项目或项目列表为空时返回空数组
    if (!MyProject || !MyProject.MyProject || MyProject.MyProject.length === 0) {
      return res.status(200).json({ 
        code: 200, 
        msg: "获取成功", 
        data: [] 
      });
    }

    let MyProjectAndAdmins = [];
    MyProjectAndAdmins = await Promise.all(
      MyProject.MyProject.map(async (project) => {
        project = project.get({ plain: true });
        let { Member } = (
          await Project.findOne({
            where: { id: project.id },
            attributes: [],
            include: [
              {
                model: User,
                as: "Member",
                attributes: ["realName"],
                through: { where: { isAdmin: true }, attributes: [] },
              },
            ],
          })
        ).get({ plain: true });
        Member = Member.map((item) => item.realName);
        project.admins = Member;
        return project;
      })
    );

    res.status(200).json({ 
      code: 200, 
      msg: "获取成功", 
      data: MyProjectAndAdmins 
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: 500, errorMsg: error.message });
  }
};

// 获取项目成员列表{id,realName}  //用于快速创建中选择项目成员
exports.getProjectMembers = async (req, res) => {
  const { projectId } = req.params;
  try {
    const project = await Project.findOne({ where: { id: projectId } });
    if (!project) {
      return res.status(404).send("未找到项目");
    }

    // const members = await User.findAll({
    //   where: { id: project.userId },
    //   attributes: ["id", "realName"],
    // });

    const members = await project.getMember({
      attributes: ["id", "realName"],
    });

    const updatedMembers = members.map((member) => {
      // 使用 Sequelize 的 get 方法来获取一个纯对象，排除 Sequelize 实例属性
      member = member.get({ plain: true });
      // const { user_project, ...rest } = member; // 使用对象解构来从member中排除user_project属性
      return member; // 返回新对象
    });
    res.status(200).json({ code: 200, msg: "获取成功", data: updatedMembers });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: 500, errorMsg: error.message });
  }
};

// 添加团队成员
exports.addMember = async (req, res) => {
  const { userId, projectId } = req.body;
  try {
    const user = await User.findOne({ where: { id: userId } });
    const project = await Project.findOne({ where: { id: projectId } });

    if (!user || !project) {
      return res.status(404).send("未找到");
    }
    const userProject = await UserProject.findOne({
      where: { userId, projectId },
    });

    if (userProject) {
      return res.status(404).send("该成员已加入项目");
    }

    // 创建关联
    await user.addProject(project);
    res.status(201).send("successfully");
  } catch (error) {
    console.error(error);
    res.status(500).send("Error");
  }
};

// 通过邀请码加入项目
exports.joinProject = async (req, res) => {
  const { invitationCode } = req.query;
  const userId = req.user.id;
  try {
    const project = await Project.findOne({ where: { invitationCode } });
    if (!project) {
      return res.status(404).json({ code: 404, errorMsg: "邀请码错误" });
    }
    const userProject = await UserProject.findOne({
      where: { userId, projectId: project.id },
    });
    if (userProject) {
      return res.status(400).json({ code: 400, errorMsg: "您已加入项目" });
    }

    // 创建关联
    const user = await User.findOne({ where: { id: userId } });
    await user.addMyProject(project);
    res.status(201).json({ code: 201, msg: "加入项目成功" });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: 500, errorMsg: error.message });
  }
};

// 点击切换是否为管理员
exports.addAdmin = async (req, res) => {
  const projectId = req.params.projectId;
  const userId = req.query.userId;
  const loginUserId = req.user.id;

  try {
    // 确保登录用户是项目创建者
    const project = await Project.findOne({ where: { id: projectId } });
    if (project.creatorId !== loginUserId) {
      return res.status(403).json({ code: 403, errorMsg: "无权限" });
    }

    // 确保要更新的用户在项目团队中
    const userProject = await UserProject.findOne({
      where: { userId, projectId },
    });
    if (!userProject) {
      return res
        .status(404)
        .json({ code: 404, errorMsg: "用户不存在于项目团队中" });
    }

    // 更新关联记录中的 isAdmin 字段
    const [updatedRows] = await UserProject.update(
      { isAdmin: userProject.isAdmin ? false : true },
      { where: { userId, projectId } }
    );
    // 确认记录被更新
    if (updatedRows === 0) {
      return res.status(404).json({
        code: 404,
        errorMsg: "No user-project association found to update",
      });
    }
    // 此处userProject为更新前的记录
    const msg = userProject.isAdmin ? "取消管理员成功" : "设为管理员成功";

    res.status(201).json({ code: 201, msg: msg });
  } catch (error) {
    console.error(error);
    res.status(500).json({ code: 500, errorMsg: error.message });
  }
};

// 获取项目详情
exports.getProjectDetail = async (req, res) => {
  const { projectId } = req.params;
  const userId = req.user.id;

  try {
    // 检查项目是否存在
    const project = await Project.findOne({
      where: { id: projectId },
      include: [
        {
          model: User,
          as: "Member",
          attributes: ["id", "realName", "avatar"],
          through: { attributes: ["isAdmin"] }
        }
      ]
    });

    if (!project) {
      return res.status(404).json({
        code: 404,
        errorMsg: "项目不存在"
      });
    }

    // 检查用户是否是项目成员
    const isMember = project.Member.some(member => member.id === userId);
    if (!isMember) {
      return res.status(403).json({
        code: 403,
        errorMsg: "您不是该项目的成员"
      });
    }

    // 获取当前用户在该项目中的角色
    const userProject = await UserProject.findOne({
      where: { userId, projectId }
    });

    // 格式化返回数据
    const projectDetail = {
      id: project.id,
      projectName: project.projectName,
      detail: project.detail,
      status: project.status,
      invitationCode: project.invitationCode,
      createdAt: project.createdAt,
      creator: project.creator,
      creatorId: project.creatorId,
      isAdmin: userProject.isAdmin,
      members: project.Member.map(member => ({
        id: member.id,
        realName: member.realName,
        avatar: member.avatar,
        isAdmin: member.UserProject.isAdmin
      }))
    };

    res.status(200).json({
      code: 200,
      msg: "获取成功",
      data: projectDetail
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({
      code: 500,
      errorMsg: error.message
    });
  }
};
